<?php

namespace callback;

use QYS\Util\Formater;
use QYS\Protocol\Request;
use QYS\Protocol\Response;
use QYS\Socket\Callback\SwooleProcess;
use QYS\Log\Log;
use QYS\Util\Debug;
use QYS\Db\Redis;
use QYS\Db\Mysql;
use QYS\Db\Mongo;
use QYS\third\Crypto\XXTEA;
use QYS\Core\Config;
use \Yosymfony\Toml\Toml;
use Swoole\Coroutine as co;
use globalunit\utils\Config as Cnf;
use globalunit\utils\QueueHelper;
use QYS\Core\Factory as CFactory;

use globalunit\utils\UniqueMessageQueueWithDelay;

class SwooleLogProcess extends SwooleProcess
{
    private $appname;
    private $gamename;
    private $version;
    private $lasttime;
    private $workerId;
    public function __construct()
    {
    }


    public function onWorkerStart($process,$workerId,$work_num){
        $gamename=Config::get("gamename");
        $this->gamename=$gamename;

        $version=Config::get("version");
        $this->version=$version;

        $GLOBALS['GAMENAME'] = $gamename;
        $GLOBALS['VERSION'] = $version;

        $GLOBALS['WORKERID'] = $workerId;
        $this->workerId = $workerId;
        $GLOBALS['WORKERCOUNT'] = $work_num;
        if($workerId == 0){
            $r=Redis::newInstance("queue");
            $this->copyback($r);
        }
    }


    public function copyback($rediscli){
        $LOG_QUEUE_NAME = "$this->gamename-$this->gamename-logger-logqueue";
        $LOG_QUEUE_BACKUP_NAME = "$this->gamename-$this->gamename-logger-logqueuebackup";

        $LPOPRPUSH = <<<crifan
                    local v = redis.call('lpop', KEYS[1])
                    if not v then
                        return nil
                    end
                    redis.call('rpush', KEYS[2], v)
                    return v
crifan;
        $args_args = Array($LOG_QUEUE_BACKUP_NAME,$LOG_QUEUE_NAME);
        $a=$rediscli->eval($LPOPRPUSH,$args_args,2);
        while ($a){
            $a=$rediscli->eval($LPOPRPUSH,$args_args,2);
        }
    }

    public function loop(){
        $LOG_QUEUE_NAME="$this->gamename-$this->gamename-logger-logqueue";
        $LOG_QUEUE_BACKUP_NAME="$this->gamename-$this->gamename-logger-logqueuebackup";

        $params=array("worker"=>$this->workerId);
        $handler=CFactory::getInstance("handler\\LogHandler",$params);
        $r=Redis::newInstance("queue");
        try {
            $res = $r->brpoplpush($LOG_QUEUE_NAME,$LOG_QUEUE_BACKUP_NAME,10);
            if($res)
            {
                $cmd=json_decode($res,true);
                $handler->handle($cmd);
                $a = $r->lrem($LOG_QUEUE_BACKUP_NAME,$res,-1);
            }
        } catch (\Exception $e) {
            // var_dump($e);
            // break;
        }

        return true;
    }

    public function onWorkerStop($process){

    }
}
